package com.bjsxt.userscenter.springmvc.interceptor;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.bjsxt.userscenter.auth.pojo.ARoleMenu;
import com.bjsxt.userscenter.auth.service.IAuthService;
import com.bjsxt.userscenter.common.util.ConstatFinalUtil;
import com.bjsxt.userscenter.users.pojo.AAdmins;

//配置拦截器
@Component("authInterceptor")
public class AuthInterceptor extends HandlerInterceptorAdapter {
	@Resource
	private IAuthService authService;
	
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
		String info="";
		//申明作用域
		HttpSession session=request.getSession();
		AAdmins admins=(AAdmins) session.getAttribute("admins");
		if(admins==null){
			info=ConstatFinalUtil.INFO_JSON.getString("7");
			session.setAttribute("info", info);
			response.sendRedirect(request.getContextPath() + "/login.htm");
			return false;
		}
		if(admins.getId() == 1)
		{
			return true ; 
		}
		//获取url
		
		String currUrl = request.getRequestURL() + "";
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("roleId", admins.getRoleId());
		Map<String, Object> resultMap = this.authService.findCondListRoleMenuService(null, condMap);
		List<ARoleMenu> roleMenuList = (List<ARoleMenu>) resultMap.get("list");
		for (Iterator iterator = roleMenuList.iterator(); iterator.hasNext();)
		{
			ARoleMenu roleMenu = (ARoleMenu) iterator.next();
			if(currUrl.indexOf(roleMenu.getMenu().getUrl()) != -1)
			{
				
				return true ; 
			}
		}
		response.sendRedirect(request.getContextPath() + "/info/error.jsp");
		return false ; 
	}
	
}
